#!/bin/bash
#------ set work dir ------
WORK_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
pushd $WORK_DIR 1>/dev/null 2>&1

#import build func
rm -f oo.sh
if [ ! -f oo.sh ]; then
    curl https://repomaven.htres.cn/repository/yunlurepo/oo.sh > oo.sh
fi
source ./oo.sh
command -v import > /dev/null 2>&1  ||  { echo >&2 "need source oo.sh"; exit 1; }

import util/buildFun
import util/log

#------ Usage ------
if [ $# -eq 0 ]
then
    echo "Usage:build_casicloud.sh project_dir(also as project_name) env(develop,release)  "
    exit 1
fi

#------ ENV ------
# wechat api url
WECHAT_API=http://registry.doc.htyunlu.com:8888/wechat/message

# unset env
unset PROJECT_NAME
unset PUBLISH_ENV
unset BUILD_VERSION
unset REMOTE_REG

# project config
PROJECT_NAME=$1
PUBLISH_ENV=$2
PUSH=$3
PUBLISH_LATEST=latest
ROOT_DIR=/data/app
# generate build version
BUILD_VERSION=$(gen_tag_with_rev)

FINAL_STR=${BUILD_VERSION: -1}
if [ "." = "${FINAL_STR}" ]
then
    BUILD_VERSION=${BUILD_VERSION}develop
fi

# docker hub
ONLINE_REG=hub.htres.cn
DEVELOP_REG=registry.htres.cn

# default is develop
REMOTE_REG=${DEVELOP_REG}

# init env if is release
if [ "release" = "${PUBLISH_ENV}" ]
then
    BUILD_VERSION=${BUILD_VERSION/develop/release}
#    REMOTE_REG=${ONLINE_REG}
#    docker login -u admin -p XgE+CC5Vyo2n ${ONLINE_REG}
fi

if [ "local" = "${PUBLISH_ENV}" ]
then
    BUILD_VERSION=${BUILD_VERSION/develop/local}
#    REMOTE_REG=${ONLINE_REG}
#    docker login -u admin -p XgE+CC5Vyo2n ${ONLINE_REG}
fi

# init env if is preonline
if [ "preonline" = "${PUBLISH_ENV}" ]
then
    BUILD_VERSION=${BUILD_VERSION/develop/preonline}
fi

echo "PROJECT_NAME is "${PROJECT_NAME}
echo "PUBLISH_ENV is "${PUBLISH_ENV}
echo "BUILD_VERSION is "${BUILD_VERSION}
echo "DOCKER HUB is "${REMOTE_REG}

Log::AddOutput PROJECT_NAME ${PROJECT_NAME}
Log::AddOutput PUBLISH_ENV ${PUBLISH_ENV}
Log::AddOutput BUILD_VERSION ${BUILD_VERSION}
Log::AddOutput REMOTE_REG ${REMOTE_REG}

#start build
echo "START BUILD "${PROJECT_NAME}
# declare start time
start_time=`date +%s`

unset PROJECT_DIR
PROJECT_DIR=$PROJECT_NAME
if [ ! -d "$PROJECT_DIR" ]; then
    echo $PROJECT_DIR is not exists !!!
    exit 1
fi
pushd $PROJECT_DIR 1>/dev/null 2>&1

#------------------------------------
if [ -f build.oo ]; then
    builtin source ./build.oo
fi

#------------------------------------
if [ ! -n "${PUSH}" ];then
  if [ -f publish.oo ]; then
      builtin source ./publish.oo
  fi
fi

popd 1>/dev/null 2>&1

# declare end time
end_time=`date +%s`
duration=(${end_time} - ${start_time})
echo "duration is "${duration}
#--------------------------------------------------------------
Log project total build with ${duration} seconds
popd $WORK_DIR 1>/dev/null 2>&1

echo done!!!